package com.myself.ssoserver.service

import com.myself.common.service.BaseService
import com.myself.ssoserver.dto.LotteryDTO
import com.myself.ssoserver.entity.*
import com.myself.ssoserver.repository.NominationRepository
import com.myself.ssoserver.repository.TriLotteryRepository
import com.myself.ssoserver.repository.TriVersionRepository
import org.ktorm.database.Database
import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import java.math.BigDecimal
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
open class TriLotteryService(
    private val repository: TriLotteryRepository,
    private val userService: UserService,
    private val nominationRepository: NominationRepository,
    private val triVersionRepository: TriVersionRepository,
    private val database: Database
) : BaseService<TriLottery, TriLotteries>(repository) {

    open fun findByUserId(id: Int): List<TriLottery> {
        return repository.findByUserId(id)
    }

    fun validateLottery(lottery: LotteryDTO) {
        val picks = lottery.normals + lottery.special
        require( picks.all { it in 1..49 }) { "号码必须在1-49范围内" }
        require(lottery.normals.size == 6) { "主号码不能重复" }
    }

    @Transactional
    open fun buyTriReCord(triLottery: TriLottery) {
        val currentUser = userService.getCurrentUser() ?: throw IllegalStateException("登录用户未找到")
        val currentTriVersion = triVersionRepository.findCurrent()
        triLottery.userId = currentUser.id
        triLottery.version = currentTriVersion
        repository.addOne(triLottery)
    }

    @Transactional
    open fun calculateTotalPrice(): Nomination {
        val currentUser = userService.getCurrentUser() ?: throw IllegalStateException("登录用户未找到")

        val readyTriVersion = triVersionRepository.findReady()

        val list = repository.findBy { (it.versionId eq readyTriVersion.id) and (it.userId eq currentUser.id) }

        calculateMoney(list, readyTriVersion)

        return Nomination {
            status = "pending"
            version = readyTriVersion
            user = currentUser
            planAmount = list.sumOf { it.money }
            realAmount = list.sumOf { it.realMoney }
        }
    }

    open fun calculateMoney(triLotteryList: List<TriLottery>, currentTriVersion: TriVersion) {
        // 定义奖金倍数配置（根据实际需求修改）
        val prizeRatios = mapOf(
            1 to BigDecimal("100.00"), // 一等奖
            2 to BigDecimal("50.00"),  // 二等奖
            3 to BigDecimal("20.00"),  // 三等奖
            4 to BigDecimal("10.00"),  // 四等奖
            5 to BigDecimal("5.00"),   // 五等奖
            6 to BigDecimal("3.00"),   // 六等奖
            7 to BigDecimal("1.00")    // 七等奖
        )

        // 准备开奖号码集合
        val winningNumbers = setOf(
            currentTriVersion.normal1,
            currentTriVersion.normal2,
            currentTriVersion.normal3,
            currentTriVersion.normal4,
            currentTriVersion.normal5,
            currentTriVersion.normal6
        )
        val specialNumber = currentTriVersion.special

        triLotteryList.forEach { lottery ->
            // 获取用户选择的主号码
            val userNumbers = setOf(
                lottery.pick1, lottery.pick2, lottery.pick3, lottery.pick4, lottery.pick5, lottery.pick6
            )

            // 计算匹配数量
            val matchedCount = userNumbers.intersect(winningNumbers).size
            val hasSpecial = (lottery.pickSpecial == specialNumber)

            // 确定奖金等级
            val prizeLevel = when {
                matchedCount == 6 -> 1
                matchedCount == 5 && hasSpecial -> 2
                matchedCount == 5 -> 3
                matchedCount == 4 && hasSpecial -> 4
                matchedCount == 4 -> 5
                matchedCount == 3 && hasSpecial -> 6
                matchedCount == 3 -> 7
                else -> null
            }

            // 计算实际金额
            lottery.realMoney = prizeLevel?.let { level ->
                lottery.money.multiply(prizeRatios[level] ?: BigDecimal.ZERO)
            } ?: BigDecimal.ZERO

            // 添加注释信息
            lottery.comment = when {
                prizeLevel != null -> "中奖等级：$prizeLevel 级"
                else -> "未中奖"
            }
            repository.updateOne(lottery)
        }
//        database.batchUpdate(TriLotteries){
//            triLotteryList.forEach{ _ ->
//                item {
//                    set(TriLotteries.realMoney, it.realMoney)
//                }
//            }
//        }
    }
}